package youleche.com.interfaces;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import youleche.com.business.BUser;
import youleche.com.common.ParamConfigParameters;
import youleche.com.model.MUser;
import youleche.com.util.AESEncryptAndDecrypt;

public class AdminUtil {
	/**
	 * 判断是不是管理员登陆
	 * @param request 请求对象
	 * @param response 响应对象
	 * @return true-登陆并且是管理员  false-没有登陆或者不是管理员
	 */
	public static boolean isAdmin(HttpServletRequest request, HttpServletResponse response){
		Cookie[] cookies = request.getCookies();
		if(cookies == null || cookies.length == 0 ||cookies.length == 1){
			return false;
		}
		
		String userName = "";
		
		boolean result = false;
		for(int i=0 ;i<cookies.length;i++){
			if(!cookies[i].getName().equals("JSESSIONID") && "youleche.s".equals(cookies[i].getName())){
				String cookieVlaue = cookies[i].getValue();
				ParamConfigParameters paramConfig = new ParamConfigParameters();
				String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
				try {
					String nameAndPass = AESEncryptAndDecrypt.decrypt(cookieVlaue, loginCode_KEY);
					if(!nameAndPass.contains("^")){
						result = false;
						break;
					}

					String sessionKey = (String) request.getSession().getAttribute(""+nameAndPass.split("\\^")[0]+"");
					if("".equals(sessionKey)){
						result = false;
						break;
					}
					
					if(cookieVlaue.equals(sessionKey)){
						userName = nameAndPass.split("\\^")[0];
						result = true;
						break;
					}else{
						result = false;
						break;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		}
		
		if(result){
			BUser handler = new BUser();
			try {
				
				MUser user = handler.getUserByUserName(userName);
				String a3_limit = user.getA3();
				if("".equals(a3_limit)){
					a3_limit = "0";
				}
				
				int limit = Integer.parseInt(a3_limit);
				if(limit < 3){
					return false;
				}
				
				return true;
			} catch (Exception e) {
				return false;
			}
		}
		
		return false;
	}
}
